package com.example8.multi_datasource.service;

import com.example8.multi_datasource.entity.source.User;
import com.example8.multi_datasource.entity.target.CustomerDO;
import com.example8.multi_datasource.mapper.source.UserMapper;
import com.example8.multi_datasource.mapper.target.CustomerMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @Description 测试服务
 * @Author lihw
 * @Date 2024/3/26 14:35
 */
@Slf4j
@Service
public class TestService {

    final CustomerMapper customerMapper;
    final UserMapper userMapper;
    private final PlatformTransactionManager primaryTransactionManager;
    private final PlatformTransactionManager secondaryTransactionManager;

    public TestService(CustomerMapper customerMapper, UserMapper userMapper, PlatformTransactionManager primaryTransactionManager, PlatformTransactionManager secondaryTransactionManager) {
        this.customerMapper = customerMapper;
        this.userMapper = userMapper;
        this.primaryTransactionManager = primaryTransactionManager;
        this.secondaryTransactionManager = secondaryTransactionManager;
    }

    @PostConstruct
    public void testTarget() {
        datasourceTest();
    }

    public void datasourceTest() {
        List<CustomerDO> customerDOS = customerMapper.queryList();
        log.info("target数据源测试数据: {}", customerDOS);

        List<User> userList = userMapper.getUserList();
        log.info("source数据源测试数据: {}", userList);
    }

    public void transactionalTest() {
        // 创建第一个数据源的事务定义
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        // 事务1
        TransactionStatus transactionOne = primaryTransactionManager.getTransaction(def);
        // 事务2
        TransactionStatus transactionTwo = secondaryTransactionManager.getTransaction(def);

        try{
            // 业务代码

            // 提交
            primaryTransactionManager.commit(transactionOne);
            secondaryTransactionManager.commit(transactionTwo);
        }catch (Exception e) {
            // 回滚
            primaryTransactionManager.rollback(transactionOne);
            secondaryTransactionManager.rollback(transactionTwo);
            throw e;
        }



    }

}
